<template>
  <div class="cropperItems" v-show="cropperShadeShow">
    <div id="demo">
      <!-- 遮罩层 -->
      <div class="container" v-show="panel">
        <div>
          <img id="image" :src="url" alt="Picture">
        </div>
        <div class="button flex-space-between">
          <button type="button" @click="cancel">取消</button>
          <button type="button" id="button" @click="crop">确定</button>
        </div>
      </div>
<!--      上传前-->
      <div style="padding:20px;">
<!--        <div class="show">-->
<!--          <div class="picture" :style="'backgroundImage:url('+headerImage+')'">-->
<!--          </div>-->
<!--        </div>-->
        <div class="uploadBeforeImg" style="margin-top:20px;" >
          <input type="file" ref="uploadBeforeImg" style="display: none" id="change" accept="image" @change="change">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Cropper from 'cropperjs'
  import 'cropperjs/dist/cropper.css'
  import {GETTOKEN, SAVEBACKGROUND} from "../apis/mine";
  import * as qiniu from "qiniu-js";
  export default {
    components: {

    },
    data () {
      return {
        headerImage:'',
        picValue:'',
        cropper:'',
        croppable:false,
        panel:false,
        url:'',
        cropperShadeShow:false,
      }
    },
    // aspectRatio 1 圆形 16 / 9 长方形
    props:["aspectRatio"],
    mounted () {
      this.$nextTick(()=>{
        this.initCropper()
      })
    },
    methods: {
      //初始化这个裁剪框
      initCropper(){
        var self = this;
        var image = document.getElementById('image');
        this.cropper = new Cropper(image, {
          aspectRatio: this.aspectRatio*1==1?1:750 / 233,//比例
          viewMode:3,//定义cropper的视图模式
          // dragMode:"move",//定义cropper的拖拽模式‘crop’: 可以产生一个新的裁剪框 ‘move’: 只可以移动裁剪框 ‘none’: 什么也不处理
          background:false,
          autoCropArea:1,//定义自动裁剪面积大小和图片进行对比 默认：0.8；
          scalable:false,//是否允许缩放图像 默认：true
          zoomable:false,//是否允许放大图像 默认：true
          ready: function () {
            self.croppable = true;
          }
        });
      },
      // 获取图片路径
      getObjectURL (file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
          url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
          url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
          url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
      },

      clickUploadBeforeImg(){
        this.cropperShadeShow = true;
        this.$refs.uploadBeforeImg.click();
      },

      // 取消
      cancel(){
        this.panel = false;
        this.cropperShadeShow = false;
      },
      // 点击上传文件
      change (e) {
        let files = e.target.files || e.dataTransfer.files;
        if (!files.length) return;
        // 只有图片可以上传 其他格式不可以上传
        if (!(files[0].type == "image/jpeg" || files[0].type == "image/png" || files[0].type == "image/jpg")){
          this.cropperShadeShow = false;//裁剪框隐藏
          this.$toast("请上传图片！")
          return;
        }
        this.panel = true;
        this.picValue = files[0];

        this.url = this.getObjectURL(this.picValue);
        //每次替换图片要重新得到新的url
        if(this.cropper){
          this.cropper.replace(this.url);
        }
        this.panel = true;

      },
      // 确认裁剪
      crop () {
        this.panel = false;
        var croppedCanvas;
        var roundedCanvas;

        if (!this.croppable) {
          return;
        }
        // Crop
        let canvasInit = {
          width:375,
          height:211
        }
        croppedCanvas = this.cropper.getCroppedCanvas(this.aspectRatio*1==1?canvasInit:'');

        // Round
        roundedCanvas = this.getRoundedCanvas(croppedCanvas);

        var headerImage = roundedCanvas.toDataURL();
        this.dataURLtoBlob(headerImage,'image/jpeg')
      },
      getRoundedCanvas (sourceCanvas) {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var width = sourceCanvas.width;
        var height = sourceCanvas.height;
        canvas.width = width;
        canvas.height = height;

        context.imageSmoothingEnabled = true;
        context.drawImage(sourceCanvas, 0, 0, width, height);
        context.globalCompositeOperation = 'destination-in';
        context.beginPath();
        // 1  画圆形 其他 画长方形
        this.aspectRatio*1==1 ?
          // 画圆形
          context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true):
          // 画长方形
          context.rect(0,0,width,height)
        context.fill();

        return canvas;
      },
      //将base64格式图片转换为文件形式
      dataURLtoBlob(dataurl,type) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        var fileData =  new Blob([u8arr], {type:type})
        let fileOfBlob = new File([fileData],new Date().getTime() + '.jpg');//重命名
        this.uploadImg(fileOfBlob)
      },
      // 上传图片
      uploadImg (form) {
        // console.log(e);
        let that = this;
        let file = form;
        var  uploadInit ;
        let getToken = GETTOKEN
        getToken()
          .then(res => {
            // console.log(res)
            if(res.data.code*1==200) {
              uploadInit=res.data.data;
              if (uploadInit=="") { return; }
              this.uploadDomain ="http://up-z1.qiniup.com/";
              let key = new Date().getTime() + file.name;
              let config = {
                chunkSize: 8,
                region: qiniu.region.z1,
                domain: this.uploadDomain
              };
              var putExtra = {

                ...config,
              }
              // console.log(qiniu);

              let observable = qiniu.upload(file, key, uploadInit, putExtra, config);
              let subscription = observable.subscribe({
                next(res){
                  let process = res.total.percent;
                  that.process = Math.floor(process);
                },
                error(err){
                  Toast.fail("上传失败：" + err.message);
                },
                complete(res){
                  that.headerImage="http://oss.dayinyun.com/"+res.key;
                  that.aspectRatio*1==1?
                    //导出图片路径
                    that.emitImgUrl():
                    //保存背景图
                    that.saveBackground();
                }
              });
            }
          })
      },
      // 导出图片路径
      emitImgUrl(){
        this.cropperShadeShow = false;//上传背景弹框隐藏
        this.$emit("emitImgUrl",this.headerImage)
      },
      // 保存用户背景图片
      saveBackground(){
        let saveBackground=SAVEBACKGROUND;
        let params = {
          background:this.headerImage,//背景图
        }
        saveBackground(params).then(res=>{
          this.cropperShadeShow = false;//上传背景弹框隐藏
          this.$emit("saveBackground")
        })
      },
    }
  }
</script>

<style lang="less" scoped>
  @import (reference) url(../assets/less/common);
  *{
    margin: 0;
    padding: 0;
  }
  .cropperItems{
    width:100%;
    position: fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
    bottom:0;
    z-index:100;
  }
  #demo .button {
    position: absolute;
    right: 0.3rem;
    left: 0.3rem;
    bottom: 0.4rem;
    button{
      border:none;
      background:none;
      font-size:@fontSize26;
      font-family: @fontFamily500;
      font-weight: @fontWeight400;
      color:@whiteColor
    }
  }
  #demo .show {
    width: 100px;
    height: 100px;
    overflow: hidden;
    position: relative;
    border-radius: 50%;
    border: 1px solid #d5d5d5;
  }
  #demo .picture {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  #demo .uploadBeforeImg{
    color:#ffffff;
  }
  #demo .container {
    z-index: 99;
    position: fixed;
    padding-top: 60px;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background:rgba(0,0,0,1);
  }

  #demo #image {
    max-width: 100%;
  }
</style>
